package com.jsy.filter;

import com.jsy.common.constant.AuthorizeConstant;
import com.jsy.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        if (!path.startsWith("/api/user/login")&&!path.startsWith("/api/user/add")){
            String token = request.getHeaders().getFirst(AuthorizeConstant.AUTHORIZE_TOKEN);
            if (StringUtils.isEmpty(token)){
                 token = request.getQueryParams().getFirst(AuthorizeConstant.AUTHORIZE_TOKEN);
            }
            if (StringUtils.isEmpty(token)){
                HttpCookie cookie = request.getCookies().getFirst(AuthorizeConstant.AUTHORIZE_TOKEN);
                if (cookie!=null){
                    token=cookie.getValue();
                }
            }
            if (StringUtils.isEmpty(token)){
                response.setStatusCode(HttpStatus.METHOD_NOT_ALLOWED);
                return response.setComplete();
            }
            try {
//                Claims claims = JwtUtil.parseJWT(token);
//                request.mutate().header(AuthorizeConstant.AUTHORIZE_TOKEN,claims.toString());
                if (!token.toLowerCase().startsWith("bearer ")){
                    token="bearer "+token;
                }
                request.mutate().header(AuthorizeConstant.AUTHORIZE_TOKEN,token);
            } catch (Exception e) {
                e.printStackTrace();
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
